package com.ihighest.app.infox.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.AppKit;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.AssignmentCenteringActivity;
import com.ihighest.app.infox.activity.InformationActivity;
import com.ihighest.app.infox.activity.InformationalContentActivity;
import com.ihighest.app.infox.activity.LoginActivity;
import com.ihighest.app.infox.adapter.NewsAdapter;
import com.ihighest.app.infox.adapter.RealtimeHotNewsAdapter;
import com.ihighest.app.infox.myview.InvitedFriendDialog;
import com.ihighest.app.infox.myview.VerticalViewPager;
import com.ihighest.app.infox.myview.VerticalViewPager.VerticalViewPagerScheduler;
import com.ihighest.app.infox.tools.CheckNetWork;

public class CopyOfNewsFragment extends Fragment implements OnClickListener {
	final static String TAG = "NewsFragment";
	Activity activity;
	// ArrayList<Object> newsList = new ArrayList<Object>();
	// PullToRefreshListView mListView;
	// ListView mListView;
	PullToRefreshListView mRefreshListView;
	NewsAdapter mAdapter;
	String text;
	String sort;
	private Context context;
	public final static int SET_NEWSLIST = 0;
	private int posotion;
	private LinearLayout inviteFriend;
	String channel_id;
	private JSONArray array;
	int page = 1;
	private JSONArray moreArray;
	long time;
	private ReflashBroadcast reflashBroadcast;
	// private TextView information_RealTimeHotSpots;
	// private RelativeLayout hotNewsLayout;

	private VerticalViewPager hotnewsViewPager;
	VerticalViewPagerScheduler scheduler;
	private Intent intent;
	private int detail = 0;
	TextView emptyview;
	TextView haveNewMessage;
	View inviteFriend_line;
	private final String READ_NEWS_ID = "readnewsid";
	private PopupWindow mPopupWindow;
	private int newDateNumber;// 新数据的个数
	int isFirst = 0;
	private JSONArray hotNewsArray;

	private boolean isGetData;// 是否正在加载数据
	String shareId;

	public CopyOfNewsFragment() {

	}

	public CopyOfNewsFragment(Context context) {
		this.context = context;
	}

	public CopyOfNewsFragment(Context context, int position) {
		this.context = context;
		this.posotion = position;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		Bundle args = getArguments();
		text = args != null ? args.getString("text") : "";
		channel_id = args != null ? args.getString("id") : "";
		sort = args != null ? args.getString("sort") : "";
		// setData();
		super.onCreate(savedInstanceState);
	}

	private void setData() {
		loadRealtimeHotNews();
		if (SharedPreferencesKit.getJsonArray(context, text + channel_id) == null
				|| SharedPreferencesKit.getJsonArray(context, text + channel_id).length() == 0) {
			getmData();
		} else {
			array = SharedPreferencesKit.getJsonArray(context, text + channel_id);
		}

	}

	private void getmData() {
		if (CheckNetWork.isConnected(context)) {
			ApiParam param = ApiParam.create();
			param.addParam("cid", channel_id);
			param.addParam("sort", sort);
			param.addParam("page", page);
			if (page >= 2) {
				param.addParam("time", time);
			}
			Api.get("channel/infos", param, new ApiCallback(context, true) {

				@Override
				public void handleSuccess(ApiResult result) {

					array = result.getDatas();
				}

				@Override
				public void handleFailure(Exception e, String msg) {

				}
			}, context);
		}

	}

	@Override
	public void onAttach(Activity activity) {
		this.activity = activity;
		super.onAttach(activity);
	}

	/** 此方法意思为fragment是否可见 ,可见时候加载数据 */
	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		Bundle args = getArguments();
		text = args != null ? args.getString("text") : "";
		channel_id = args != null ? args.getString("id") : "";
		sort = args != null ? args.getString("sort") : "";
		if (isVisibleToUser) {
			System.out.println(text + "可见");
			// initPupu();
			// if (isFirst == 2) {
			// isFirst = 1;
			// }
			reflashBroadcast = new ReflashBroadcast();
			IntentFilter filter = new IntentFilter();
			filter.addAction(Const.REFLASH);
			context.registerReceiver(reflashBroadcast, filter);
			// if (array != null && array.length() != 0) {
			// handler.obtainMessage(SET_NEWSLIST).sendToTarget();
			// } else {
			// new Thread(new Runnable() {
			// @Override
			// public void run() {
			// // TODO Auto-generated method stub
			// try {
			// Thread.sleep(2);
			// } catch (InterruptedException e) {
			// // TODO Auto-generated catch block
			// e.printStackTrace();
			// }
			// handler.obtainMessage(SET_NEWSLIST).sendToTarget();
			// }
			// }).start();
			// }
			getData();
			// loadRealtimeHotNews();

		} else {
			if (mPopupWindow != null) {
				mPopupWindow = null;
			}
			// fragment不可见时不执行操作
			try {
				if (reflashBroadcast != null) {
					context.unregisterReceiver(reflashBroadcast);
				}
			} catch (IllegalArgumentException e) {
				if (e.getMessage().contains("Receiver not registered")) {
					// Ignore this exception. This is exactly what is desired
				} else {
					throw e;
				}
			}
			mPopupWindow = null;
		}
		super.setUserVisibleHint(isVisibleToUser);
	}

	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case SET_NEWSLIST:
				if (mAdapter == null) {
					mAdapter = new NewsAdapter(activity, array, text + channel_id);

				}
				mRefreshListView.setAdapter(mAdapter);
				if (hotNewsArray.length() > 0) {
					if (scheduler != null) {
						scheduler.stop();
					}
					hotnewsViewPager.setVisibility(View.VISIBLE);
					hotnewsViewPager.setAdapter(new RealtimeHotNewsAdapter(context, hotNewsArray));
					hotnewsViewPager.getAdapter().notifyDataSetChanged();
					scheduler = new VerticalViewPagerScheduler(hotnewsViewPager);
					scheduler.updateCount(hotNewsArray.length());
					scheduler.restart(5 * 1000);
					// information_RealTimeHotSpots.setMovementMethod(ScrollingMovementMethod.getInstance());
					// information_RealTimeHotSpots.setText(result.getDatas().getJSONObject(0).getString("title"));
					// information_RealTimeHotSpots.setTag(result.getDatas().getJSONObject(0).getString("id"));
				} else {
					hotnewsViewPager.setVisibility(View.GONE);
				}
				break;

			}
			super.handleMessage(msg);
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = View.inflate(context, R.layout.infox_fragment_newstext, null);
		initView(view);
		loadRealtimeHotNews();
		return view;
	}

	/**
	 * 控件初始化绑定
	 * 
	 * @param view
	 * 
	 * @author lkx Created at 2015-10-20 上午11:24:30
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void initView(View view) {
		mRefreshListView = (PullToRefreshListView) view.findViewById(R.id.pullToRefresh);
		View v = View.inflate(context, R.layout.infox_fragment_head, null);
		inviteFriend = (LinearLayout) v.findViewById(R.id.inviteFriend);
		inviteFriend_line = v.findViewById(R.id.inviteFriend_line);
		// hotNewsLayout = (RelativeLayout) v.findViewById(R.id.hotNewsLayout);
		hotnewsViewPager = (VerticalViewPager) v.findViewById(R.id.hotnews_viewpager);
		// haveNewMessage = (TextView) view.findViewById(R.id.haveNewEssay);
		// mListView = (ListView) view.findViewById(R.id.newsList);
		mRefreshListView.getRefreshableView().addHeaderView(v, null, false);
		// information_RealTimeHotSpots = (TextView)
		// v.findViewById(R.id.information_RealTimeHotSpots);
		view.findViewById(R.id.informationSignin).setOnClickListener(this);
		view.findViewById(R.id.informationInvitedFriend).setOnClickListener(this);
		// information_RealTimeHotSpots.setOnClickListener(this);
		if (posotion != 0) {
			inviteFriend.setVisibility(View.GONE);
			inviteFriend_line.setVisibility(View.GONE);
		} else {
			inviteFriend.setVisibility(View.VISIBLE);
			inviteFriend_line.setVisibility(View.VISIBLE);
		}
		mAdapter = new NewsAdapter(context, array, text + channel_id);
		mRefreshListView.setAdapter(mAdapter);
		emptyview = new TextView(context);
		emptyview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
		emptyview.setText("加载中 ...");
		emptyview.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
		emptyview.setVisibility(View.GONE);
		mRefreshListView.setEmptyView(emptyview);
		mRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				detail = 1;
				try {
					String getReadNewsId = SharedPreferencesKit.getString(context, READ_NEWS_ID, null);
					String readNewsId = null;
					String itemid = ((TextView) view.findViewById(R.id.tv_id)).getText().toString();
					if (TextUtils.isEmpty(getReadNewsId)) {
						// 如果获取到的读取的新闻id为空，证明还没有读取新闻
						// readNewsId = array.getJSONObject(position -
						// 2).getString("id");
						readNewsId = itemid;
					} else {
						// 如果不为空将数据进行拼接
						// readNewsId = getReadNewsId + "#" +
						// array.getJSONObject(position - 2).getString("id");
						readNewsId = getReadNewsId + "#" + itemid;
					}

					SharedPreferencesKit.putString(context, READ_NEWS_ID, readNewsId);
					mAdapter.notifyDataSetChanged();
					Intent intent = new Intent(getActivity(), InformationalContentActivity.class);

					// intent.putExtra("newsId", array.getJSONObject(position -
					// 2).getString("id"));
					intent.putExtra("newsId", itemid);
					startActivity(intent);
				} catch (Exception e) {
					Log.e(TAG, e.getMessage(), e);
				}

			}
		});

		mRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				emptyview.setText("加载中 ...");
				page = 1;
				isFirst = 1;
				if (mPopupWindow == null) {
					initPupu();
				}
				if (CheckNetWork.isConnected(context)) {
					getData();
				} else {
					ToastKit.showShort(context, "请连接网络");
					mRefreshListView.onRefreshComplete();
				}

			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				page++;
				if (page == 2) {
					time = SharedPreferencesKit.getLong(context, text + channel_id + "time");
				}
				if (CheckNetWork.isConnected(context)) {
					// System.out.println("请求" + System.currentTimeMillis());
					getData();
				} else {

					ToastKit.showShort(context, "请连接网络");
				}
			}

		});
		mRefreshListView.setOnScrollListener(new OnScrollListener() {
			private int lastItem;

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				// mRefreshListView//设置listview的当前位置，如果不设置每次加载
				// if (scrollState == OnScrollListener.SCROLL_STATE_IDLE &&
				// lastItem == mAdapter.getCount() - 1) {
				// Log.i(TAG, "onScrollStateChanged");
				// // 加载数据代码，此处省略了
				// }
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				// Log.d("mRefreshListView", "onScroll方法执行 firstVisibleItem：：" +
				// firstVisibleItem);
				// Log.d("mRefreshListView", "onScroll方法执行 visibleItemCount：：" +
				// visibleItemCount);
				// Log.d("mRefreshListView", "onScroll方法执行 totalItemCount：：" +
				// totalItemCount);
				// lastItem = firstVisibleItem + visibleItemCount;// 判断是否滑到底部的值
				// Log.d("mRefreshListView", "onScroll方法执行 lastItem：" +
				// lastItem);
				if (firstVisibleItem > (totalItemCount - visibleItemCount - 2)) {

					page++;
					if (page == 2) {
						time = SharedPreferencesKit.getLong(context, text + channel_id + "time");
					}
					if (CheckNetWork.isConnected(context)) {
						// System.out.println("请求" +
						// System.currentTimeMillis());
						if (isGetData) {
							return;
						} else {
							getData();
						}

					} else {

						ToastKit.showShort(context, "请连接网络");
					}

				}
			}
		});
		// initPupu();
		// getData();
	}

	/**
	 * 初始化新数据弹窗
	 * 
	 * 
	 * @author lkx Created at 2015-11-10 下午6:27:58
	 */
	private void initPupu() {
		LayoutInflater layoutInflater = LayoutInflater.from(context);
		View popupWindow = layoutInflater.inflate(R.layout.infox_have_newspupo, null);
		haveNewMessage = (TextView) popupWindow.findViewById(R.id.haveNewEssay);
		// 创建一个PopupWindow
		// 参数1：contentView 指定PopupWindow的内容
		// 参数2：width 指定PopupWindow的width
		// 参数3：height 指定PopupWindow的height
		mPopupWindow = new PopupWindow(popupWindow, android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
		// 必须设置背景
		// mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击其他地方 就消失 (只设置这个，没有效果)

		// mPopupWindow.setOutsideTouchable(true); /* 设置触摸外面时消失 */

	}

	boolean isNewPage = true;

	/**
	 * 获取数据
	 * 
	 * 
	 * @author lkx Created at 2015-10-20 上午11:46:54
	 */
	private void getData() {
		if (CheckNetWork.isConnected(context)) {
			ApiParam param = ApiParam.create();
			param.addParam("cid", channel_id);
			param.addParam("sort", sort);
			param.addParam("page", page);
			if (page >= 2) {
				param.addParam("time", time);
			}
			isGetData = true;
			Api.get("channel/infos", param, new ApiCallback(context, true) {

				@Override
				public void handleSuccess(ApiResult result) {
					// System.out.println("获取到" + System.currentTimeMillis());
					if (result.getDatas() == null || result.getDatas().length() == 0) {
						if (page == 1) {
							JSONArray jsonArray = SharedPreferencesKit.getJsonArray(context, text + channel_id);
							if (jsonArray == null || jsonArray.length() == 0) {
								emptyview.setText("暂无数据");
							} else {
								mAdapter.setData(jsonArray);
							}

						} else {
							page = page > 1 ? --page : 1;
						}
					} else {
						isNewPage = false;
						if (page == 1) {
							if (isFirst != 2 && isFirst != 0) {
								System.out.println("新闻列表刷新");
								if (isEquals(result.getDatas(), (SharedPreferencesKit.getJsonArray(context, text + channel_id)))) {
									// 如果数据有变动
									haveNewData();
								}
							}

							SharedPreferencesKit.putJsonArray(context, text + channel_id, result.getDatas());
							mAdapter.setData(result.getDatas());
						} else {

							moreArray = result.getDatas();
							try {
								array = AppKit.joinJSONArray(array, moreArray);
							} catch (JSONException e) {
								Log.e(TAG, e.getMessage(), e);
							}
							mAdapter.appendData(moreArray);
						}
						if (page == 1) {
							SharedPreferencesKit.putLong(context, text + channel_id + "time", result.getTime());
						}
						time = result.getTime();
					}
					isGetData = false;
					mRefreshListView.onRefreshComplete();
				}

				@Override
				public void handleFailure(Exception e, String msg) {
					Log.e(TAG, msg, e);
					isGetData = false;
					emptyview.setText("加载失败，请重新刷新数据");
					mRefreshListView.onRefreshComplete();
				}
			}, context);
		} else {
			array = SharedPreferencesKit.getJsonArray(context, text + channel_id);
			if (array == null || array.length() == 0) {
				if (emptyview != null) {
					emptyview.setText("暂无数据");
				}

			} else {
				if (mAdapter != null) {
					mAdapter.setData(array);
				}
			}

		}
		loadRealtimeHotNews();
	}

	private void loadRealtimeHotNews() {
		if ("Recommend".equalsIgnoreCase(sort)) {
			Api.data("hot_news_list.json", new ApiCallback(context, true) {

				@Override
				public void handleSuccess(ApiResult result) {
					try {
						if (result.getDatas().length() > 0) {
							if (scheduler != null) {
								scheduler.stop();
							}
							hotnewsViewPager.setVisibility(View.VISIBLE);
							hotNewsArray = result.getDatas();
							hotnewsViewPager.setAdapter(new RealtimeHotNewsAdapter(context, result.getDatas()));
							hotnewsViewPager.getAdapter().notifyDataSetChanged();
							scheduler = new VerticalViewPagerScheduler(hotnewsViewPager);
							scheduler.updateCount(result.getDatas().length());
							scheduler.restart(5 * 1000);
							// information_RealTimeHotSpots.setMovementMethod(ScrollingMovementMethod.getInstance());
							// information_RealTimeHotSpots.setText(result.getDatas().getJSONObject(0).getString("title"));
							// information_RealTimeHotSpots.setTag(result.getDatas().getJSONObject(0).getString("id"));
						} else {
							hotnewsViewPager.setVisibility(View.GONE);
						}
					} catch (Exception e) {
						Log.e(TAG, e.getMessage(), e);
					}
				}

				@Override
				public void handleFailure(Exception e, String msg) {
					hotnewsViewPager.setVisibility(View.GONE);

				}
			}, context);
		}
	}

	/**
	 * 如果有新数据
	 * 
	 * @param lengh
	 * 
	 * @author lkx Created at 2015-11-10 下午6:45:14
	 */
	private void haveNewData() {
		if (Const.INTO_GUIDE) {
			return;
		}
		if (mPopupWindow != null) {
			haveNewMessage.setText("已为您加载新数据");
			showPupop();

		}
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// haveNewMessage.setText("以为您加载" + lengh +
				// "条新数据");
				// haveNewMessage.setVisibility(View.VISIBLE);
				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {
						// haveNewMessage.setVisibility(View.GONE);
						if (mPopupWindow != null) {
							mPopupWindow.dismiss();
						}

						mPopupWindow = null;
					}
				}, 1000);
			}
		}, 0);
	}

	@Override
	public void onClick(View view) {

		switch (view.getId()) {
		case R.id.informationSignin:
			if (TextUtils.isEmpty(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID))) {
				intent = new Intent(context, LoginActivity.class);
				ToastKit.showShort(activity, Const.UN_LOGIN_ALERT);
			} else {
				intent = new Intent(context, AssignmentCenteringActivity.class);
			}
			startActivity(intent);
			break;

		case R.id.informationInvitedFriend:

			if (TextUtils.isEmpty(SharedPreferencesKit.getString(context, Const.SP_KEY_USER_ID))) {
				intent = new Intent(context, LoginActivity.class);
				ToastKit.showShort(activity, Const.UN_LOGIN_ALERT);
				startActivity(intent);
			} else {
				Api.get("share", ApiParam.create().addParam("type", "AppLoad"), new ApiCallback(context) {

					@Override
					public void handleFailure(Exception e, String msg) {
					}

					@Override
					public void handleSuccess(ApiResult result) {

						try {
							InvitedFriendDialog dialog = new InvitedFriendDialog(getActivity(), R.style.CustomDialog);
							shareId = result.getData().getString("ShareId");

							dialog.setShareId(shareId);
							dialog.show();
						} catch (JSONException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}
				}, context);
			}
			break;
		// case R.id.information_RealTimeHotSpots:
		// Intent detailIntent = new Intent(context,
		// InformationalContentActivity.class);
		// detailIntent.putExtra("newsId",
		// information_RealTimeHotSpots.getTag().toString());
		// startActivity(detailIntent);
		// break;
		}

	}

	@Override
	public void onResume() {
		System.out.println(text + "onResume");
		if (detail == 0) {

			array = SharedPreferencesKit.getJsonArray(context, text + channel_id);
			// if (array != null || array.length() != 0) {
			// // 如果缓存数据不为空
			// // mAdapter = new NewsAdapter(context, array, text +
			// // channel_id);
			// // mRefreshListView.setAdapter(mAdapter);
			// if (CheckNetWork.isConnected(context)) {
			// getData();
			// } else {
			//
			// // mAdapter = new NewsAdapter(context, array, text +
			// // channel_id);
			// // mRefreshListView.setAdapter(mAdapter);
			// if (array == null || array.length() == 0) {
			// emptyview.setText("暂无数据");
			// } else {
			// mAdapter.setData(array);
			// }
			//
			// ToastKit.showShort(context, "请连接网络");
			// }
			// } else {

			if (isFirst == 0) {
				System.out.println(text + "onResume2");
				if (CheckNetWork.isConnected(context)) {
					mAdapter = new NewsAdapter(context, array, text + channel_id);
					mRefreshListView.setAdapter(mAdapter);
					if (array == null || array.length() == 0) {
						emptyview.setText("暂无数据");
					} else {
						mAdapter.setData(array);
					}

					isFirst = 2;
					getData();
				} else {

					mAdapter = new NewsAdapter(context, array, text + channel_id);
					mRefreshListView.setAdapter(mAdapter);
					if (array == null || array.length() == 0) {
						emptyview.setText("暂无数据");
					} else {
						mAdapter.setData(array);
					}

					ToastKit.showShort(context, "请连接网络");
				}
			}

			// }
		}
		super.onResume();
	}

	public class ReflashBroadcast extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// 得到数据变化的广播
			if (intent.getAction().equals(Const.REFLASH)) {
				page = 1;
				getData();

			}

		}

	}

	/**
	 * 显示pupop
	 * 
	 * 
	 * @author lkx Created at 2015-10-16 下午3:44:17
	 */
	private void showPupop() {
		if (mPopupWindow != null) {
			if (mPopupWindow.isShowing()) {
				mPopupWindow.dismiss();
			} else {
				mPopupWindow.showAsDropDown(InformationActivity.mRadioGroup_content, 0, 0);
			}
		}

	}

	@Override
	public void onPause() {
		// if (reflashBroadcast != null) {
		// context.unregisterReceiver(reflashBroadcast);
		// }
		isFirst = 2;
		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
		}
		super.onPause();
	}

	@Override
	public void onDestroy() {
		isFirst = 2;
		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
		}
		super.onDestroy();
	}

	@Override
	public void onDestroyView() {
		isFirst = 2;
		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
		}
		super.onDestroyView();
	}

	@Override
	public void onStop() {
		isFirst = 2;
		if (mPopupWindow != null) {
			mPopupWindow.dismiss();
			mPopupWindow = null;
		}
		super.onStop();
	}

	/**
	 * 原始数据与新数据是否相等
	 * 
	 * @param array1
	 * @param array2
	 * @return 数据相同时返回false，不同时返回true
	 * 
	 * @author lkx Created at 2015-11-11 上午10:52:14
	 */
	public boolean isEquals(JSONArray array1, JSONArray array2) {
		boolean istrue = false;
		if (array1.length() == array2.length()) {

			for (int i = 0; i < array1.length(); i++) {
				try {
					if (array1.getJSONObject(i).getString("id").equals(array2.getJSONObject(i).getString("id"))) {
						// 如果数据一样
						istrue = false;
					} else {
						newDateNumber++;
						istrue = true;
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return istrue;

	}
}
